package com.ruoyi.quartz.task;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定时任务调度测试
 * 
 * @author ruoyi
 */
@Component("ryTask")
public class RyTask {

    private static final Logger log = LoggerFactory.getLogger(RyTask.class);

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i)
    {
        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void ryParams(String params)
    {
        System.out.println("执行有参方法：" + params);
    }

    public void ryNoParams()
    {
        System.out.println("执行无参方法");
    }

    public void exportData(String url, String user, String password, String sql, String tableName, String filePath, String knowledgeId){
        String fileName = tableName + "_" + sdf.format(new Date()) + ".txt";
        File file = new File(filePath + "/" + fileName);
        List<String> fieldList = new ArrayList();
        // 数据库连接
        try(Connection connection = DriverManager.getConnection("jdbc:mysql://" + url
                + "?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8", user, password);
            FileWriter writer = new FileWriter(file)){
            // 查询表结构
            Statement stmt = connection.createStatement();
            ResultSet tableInfoRS = stmt.executeQuery("SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE, COLUMN_COMMENT\n" +
                    "FROM INFORMATION_SCHEMA.COLUMNS \n" +
                    "WHERE TABLE_NAME ='" + tableName + "'\n" +
                    "ORDER BY ordinal_position asc");
            while (tableInfoRS.next()) {
                String fieldBak = tableInfoRS.getString("COLUMN_COMMENT");
                fieldList.add(fieldBak);
            }

            // 查询数据集合
            ResultSet resultSet = stmt.executeQuery(sql);

            while (resultSet.next()) {
                StringBuffer sb = new StringBuffer();
                for(int i = 0; i < fieldList.size(); i++){
                    sb.append(fieldList.get(i) + ":" + resultSet.getString(i+1) + ";");
                }
                sb.append("\n");
                writer.write(sb.toString());
            }

            uploadFile(new File(filePath + "/" + fileName), knowledgeId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    public void difyETL(String path){
//        File folder = new File(path);
//        File[] files = folder.listFiles();
//        for (File file : files) {
//            if (file.isFile()) {
//                // 上传文件
//                uploadFile(file);
//            }
//        }
//    }

    private void uploadFile(File file, String knowledgeId){
        try (FileInputStream fileInputStream = new FileInputStream(file)){
            //接收文件的服务器地址
            String uploadURL = "http://localhost/v1/datasets/" + knowledgeId + "/document/create-by-file";

            //创建HttpClient
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(uploadURL);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(StandardCharsets.UTF_8);
            // 添加参数 high_quality
            builder.addTextBody("data", "{\"indexing_technique\":\"high_quality\"}", ContentType.create("text/plain", StandardCharsets.UTF_8));
            /*绑定文件参数，传入文件流和contenttype，此处也可以继续添加其他formdata参数*/
            builder.addBinaryBody("file", fileInputStream, ContentType.create("text/plain", StandardCharsets.UTF_8), file.getName());
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            // 认证信息
            httpPost.setHeader("Authorization", "Bearer dataset-3QdXrJH6Kj1yY0SQFUCFdu9d");

            //执行提交
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            if(responseEntity != null){
                //将响应的内容转换成字符串
                String result = EntityUtils.toString(responseEntity, Charset.forName(Constants.UTF8));
                log.warn(result);
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
}
